package com.ebupt.migu.music.schedule;

import com.ebupt.migu.music.common.util.DateUtil;
import com.ebupt.migu.music.strategy.entity.StrategyInfo;
import com.ebupt.migu.music.userGroup.entity.UserGroupInfo;
import com.ebupt.migu.music.userGroup.service.CrowdListService;
import com.ebupt.migu.music.userGroup.service.CrowdTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author lizm
 */
@Slf4j
@Component
@EnableScheduling
public class UserGroupInfoTask {
    @Autowired
    private CrowdTaskService clervice;
    @Resource
    private CrowdListService crowdListService;

    /**
     * 每天0点更新
     * 每天在固定时间将自动更新的人群的更新状态，修改为待更新
     */
    @Scheduled(cron = "${cron.updateCrowdStatus}")
    public void autoUpdateCrowdStatus() throws Exception {
        log.info("定时任务开始：autoUpdateCrowdStatus");
        clervice.autoUpdateCrowdStatus();
        log.info("定时任务结束：autoUpdateCrowdStatus,更新完成");
    }

    /**
     * 创建之后一个月内没有被引用的自动更新的人群，将会被重置为手动更新
     * 每天0点更新
     */
    @Scheduled(cron = "${cron.crowdIsInvalid}")
    public void autoCrowdIsInvalid() throws Exception {
        log.info("定时任务开始：autoCrowdIsInvalid");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String today = sdf.format(new Date());
        int i = 0;
        // 获取人群=标签人群+自动更新+非已删除
        // t.create_way in (1,2) and t.auto_update=1 and t.create_status!=9
        List<UserGroupInfo> groupList = clervice.queryCrowdList();
        if (null != groupList && groupList.size() > 0) {
            for (UserGroupInfo info : groupList) {
                boolean regroupFlag = false;
                long regroupDates = -1;
                boolean strategyFlag = false;
                long strategyDates = -1;
                boolean isTimeout = false;
                boolean is_invalid = false;
                boolean is_delete = false;
                String groupId = info.getGroupId();
                log.info("扫描人群：" + groupId + ":" + info.getUserGroupName());
                //类型一：判断人群是否补重组引用;
                //用人群ID like user_group_info.res_groups,如果结果集>=1证明 被重组引用
                //create_time倒序取第一个结果的创建时间==最近被重组引用的时间
                List<UserGroupInfo> regroupList = clervice.queryCrowdRegroupList(groupId);
                if (null != regroupList && regroupList.size() > 0) {//该人群被重组引用
                    regroupFlag = true;
                    UserGroupInfo reInfo = regroupList.get(0);
                    String isRegroupQuotedTime = sdf.format(reInfo.getCreateTime());
                    regroupDates = DateUtil.getDistanceDays(isRegroupQuotedTime, today);
                    log.info("该人群被：" + reInfo.getGroupId() + ":" + reInfo.getUserGroupName() + ":重组引用" + regroupDates + "天");
                }
                //类型二:判断是否被策略引用
                //遍历策略表，取最近被引用策略的创建时间为人群被策略引用的时间
                List<StrategyInfo> strategyList = clervice.queryStrategyAdoptedList(groupId);
                if (null != strategyList && strategyList.size() > 0) {//该人群被策略引用
                    strategyFlag = true;
                    StrategyInfo strategyInfo = strategyList.get(0);
                    String isStrategyQuotedTime = sdf.format(strategyInfo.getCreateTime());
                    strategyDates = DateUtil.getDistanceDays(isStrategyQuotedTime, today);
                    log.info("该人群被：" + strategyInfo.getStrategyId() + "：" + strategyInfo.getStrategyName() + ":策略引用:" + strategyDates + "天");

                }
                //类型三：用户群创建一个月未被引用
                long dates = DateUtil.getDistanceDays(sdf.format(info.getCreateTime()), today);
                if (regroupFlag || strategyFlag) {//被引用
                    if ((0 <= regroupDates && regroupDates < 30) || (0 <= strategyDates && strategyDates < 30)) {
                        //引用未超过30天
                    } else {
                        log.info("类型一二：失效：自动更新--手动更新");
                        isTimeout = true;
                    }
                } else {
                    if (dates > 30) {//创建超一个月+没有被引用
                        log.info("类型三：创建" + dates + "天没引用：失效：自动更新--手动更新");
                        isTimeout = true;
                    }
                    // 设置人群失效
                    if (dates > 60) {
                        is_invalid = true;
                    }
                    // 设置人群删除
                    if (dates > 180) {
                        is_delete = true;
                    }
                }
                //失效：自动更新--手动更新
                if (isTimeout) {
                    log.info("isTimeout：设置失效：自动更新--手动更新");
                    int j = clervice.updateCrowdAutoUpdateState(groupId);
                    i++;
                }
                // 超过60天设置人群失效
                if (is_invalid) {
                    clervice.updateUserGroupInfo(groupId, 8);
                }
                // 超过120删除人群
                if (is_delete) {
                    clervice.updateUserGroupInfo(groupId, 9);
                }
            }
        }
        log.info("定时任务结束：autoCrowdIsInvalid,更新：" + i);
    }

    /**
     * 每天凌晨0点重置客群洞察次数
     */
    @Scheduled(cron = "${cron.reset_insight_times}")
    @Async
    public void resetInsightTimes() {
        crowdListService.resetInsightTimes();
    }
}